package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CaheClient;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CaheClient caheClient;
    // 缓存穿透
    /*
    public Result queryById(Long id) {
        //1 从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
        //2 判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3 存在，返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        // 命中是否为空
        if (shopJson != null){
            return Result.fail("这是空值，店铺不存在！");
        }
        //4 不存在，根据id查询数据库
        Shop shop = getById(id);

        if (shop == null){
            //为解决缓存穿透 将空值写入redis
            stringRedisTemplate.opsForValue().set("cache:shop:" + id,"",2L, TimeUnit.MINUTES);
            // 返回错误信息
            return Result.fail("店铺不存在！");
        }
        //5 存在，写入redis
        stringRedisTemplate.opsForValue().set("cache:shop:" + id, JSONUtil.toJsonStr(shop),30L, TimeUnit.MINUTES);
        //6 返回
        return Result.ok(shop);
    }
     */


    @Override
    public Result queryById(Long id) {
//        //解决缓存穿透
//        Shop shop = caheClient.queryByIdWithPassThrough("cache:shop:", id, Shop.class, id2->getById(id2), 30L, TimeUnit.MINUTES);

//        //互斥锁缓存击穿
//        Shop shop = getByIdWithOptimisticLocker(id);

//        //逻辑过期缓存击穿
        Shop shop = caheClient.queryWithLogicExpire("cache:shop:", id, Shop.class, id2->getById(id2), 30L, TimeUnit.MINUTES);


        if (shop == null){
            return Result.fail("店铺不存在！");
        }
        return Result.ok(shop);
    }
//    private Shop getByIdWithOptimisticLocker(Long id) {
//        //1 从redis查询商铺缓存
//        String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
//        //2 判断是否存在
//        if (StrUtil.isNotBlank(shopJson)) {
//            //3 存在，返回
//            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
//            return shop;
//        }
//        // 命中是否为空
//        if (shopJson != null){
//            return null;
//        }
//        //4 缓存重建
//        //4.1 获取互斥锁
//        String lock = "lock:shop:" + id;
//        Shop shop = null;
//        try {
//            boolean isLock = tryLock(lock);
//            //4.2 判断是否获取成功
//            if(!isLock){
//                //4.3 失败，休眠重试
//                Thread.sleep(50);
//                getByIdWithOptimisticLocker( id);
//            }
//            //4.4 成功，根据id查询数据库
//            shop = getById(id);
//            //由于在本地重建数据库较快 在此模拟延迟
//            Thread.sleep(200);
//            if (shop == null){
//                //为解决缓存穿透 将空值写入redis
//                stringRedisTemplate.opsForValue().set("cache:shop:" + id,"",2L, TimeUnit.MINUTES);
//                // 返回错误信息
//                return null;
//            }
//            //5 存在，写入redis
//            stringRedisTemplate.opsForValue().set("cache:shop:" + id, JSONUtil.toJsonStr(shop),30L, TimeUnit.MINUTES);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        } finally {
//            //6 释放互斥锁
//            unLock(lock);
//        }
//        //6 返回
//        return shop;
//    }


    /*public void saveShop2Redis(Long id, Long expireSeconds){
        //1 查询店铺数据
        Shop  shop = getById(id);
        //2 封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3  写入redis
        stringRedisTemplate.opsForValue().set("cache:shop:" + id, JSONUtil.toJsonStr(redisData));
    }*/

    @Override
    @Transactional
    public Result updated(Shop shop) {
        Long id = shop.getId();
        if (id == null){
            return Result.fail("店铺id不能为空！");
        }
        // 1 更新数据库
        updateById( shop);
        // 2 删除缓存
        stringRedisTemplate.delete("cache:shop:" + id);
        return Result.ok();
    }
}
